package com.boc.langxiang.ui.fragment.me;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.boc.langxiang.App;
import com.boc.langxiang.Constant;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.me.OrdersReturnProductContract;
import com.boc.langxiang.entity.events.OrdersEvent;
import com.boc.langxiang.entity.response.ProductEntity;
import com.boc.langxiang.entity.response.ProductListEntity;
import com.boc.langxiang.presenter.me.OrdersReturnProductFragmentPresenter;
import com.boc.langxiang.ui.activity.me.OrdersDetailActivity;
import com.boc.langxiang.ui.adapter.me.section.OrdersRPSectionAdapter;
import com.boc.langxiang.ui.adapter.me.section.OrdersSection;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by admin on 2016/6/23.
 */
public class OrdersReturnProductFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OrdersReturnProductContract.View, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnRecyclerViewItemClickListener {

    @BindView(R.id.recylerview_me_return_product)
    RecyclerView recylerviewMeReturnProduct;
    @BindView(R.id.swipeLayout_me_return_product)
    SwipeRefreshLayout swipeLayoutMeReturnProduct;
    private OrdersRPSectionAdapter mAdapter;
    private List<OrdersSection> mList;
    private OrdersReturnProductFragmentPresenter mPresenter;
    private boolean mIsRefresh;
    private boolean mIsLoadmore;
    private int mPage;

    public static OrdersReturnProductFragment getInstance() {
        OrdersReturnProductFragment meReturnGoodsFragment = new OrdersReturnProductFragment();
        Bundle args = new Bundle();
        args.putString(Constant.ME_ALL_ORDERS, "退货");
        meReturnGoodsFragment.setArguments(args);
        return meReturnGoodsFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = View.inflate(getContext(), R.layout.fragment_me_return_product, null);
        ButterKnife.bind(this, inflate);
        EventBus.getDefault().register(this);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new OrdersReturnProductFragmentPresenter(this);
        swipeLayoutMeReturnProduct.setOnRefreshListener(this);
        swipeLayoutMeReturnProduct.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        recylerviewMeReturnProduct.setHasFixedSize(true);
        recylerviewMeReturnProduct.setLayoutManager(new LinearLayoutManager(mContext));
        initAdapter();
        initRequest();

    }

    private void initRequest() {
        mPage = 1;
        mPresenter.returnProduct(String.valueOf(mPage));
    }

    private void initAdapter() {

        mList = new ArrayList<>();

        mAdapter = new OrdersRPSectionAdapter(mContext, R.layout.item_orders_entity, R.layout.head_orders_returnproduct, R.layout.foot_orders_returnproduct, mList, this);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.view_empty, (ViewGroup) recylerviewMeReturnProduct.getParent(), false);
        mAdapter.setEmptyView(emptyView);
        mAdapter.openLoadAnimation();
        mAdapter.isFirstOnly(false);
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        recylerviewMeReturnProduct.setAdapter(mAdapter);
        recylerviewMeReturnProduct.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefresh) {
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void onRefresh() {
        if (mIsRefresh) {
            return;
        }
        mIsRefresh = true;
        mAdapter.openLoadMore(Constant.PAGE_SIZE, true);
        mPage = 1;
        mPresenter.returnProduct(String.valueOf(mPage));
    }

    @Override
    public void startDetailActivity(String id, String totalPrice, String status) {
        Intent intent = new Intent(getActivity(), OrdersDetailActivity.class);
        if (id.equals("0") || id.equals("1") || id.equals("2") || id.equals("3") || id.equals("4")) {
            id = "5";
        }
        intent.putExtra(Constant.ME_PRODUCT_ID, id);
        intent.putExtra(Constant.ME_PRODUCT_TYPE, Integer.parseInt(status));
        intent.putExtra(Constant.ME_PRODUCT_TOTALPRICE, totalPrice);
        startActivity(intent);
    }

    @Override
    public void getReturnProduct(final List<ProductListEntity> list) {
        if (!isAdded()) {
            return;
        }
        if (mIsLoadmore) {
            mIsLoadmore = false;
            if (list == null) {
                mAdapter.openLoadMore(false);
                loadDone();
                return;
            }

        } else {
            mIsRefresh = false;
            swipeLayoutMeReturnProduct.setRefreshing(false);
            mList.clear();
            if (list == null) {
                loadDone();
                mAdapter.setNewData(mList);
                mAdapter.openLoadMore(false);
                return;
            }
        }

        List<OrdersSection> ordersSections = dataExecute(list);
        mList.addAll(ordersSections);
        mAdapter.setNewData(mList);

        if (list.size() < Constant.PAGE_SIZE) {
            mAdapter.openLoadMore(false);
            loadDone();
        } else {
            mAdapter.openLoadMore(true);
        }

     /*   if (!isAdded()) {
            return;
        }
        swipeLayoutMeReturnProduct.setRefreshing(false);
        mIsRefresh = false;
        if (list == null) {
            return;
        }

        Observable.defer(new Func0<Observable<List<OrdersSection>>>() {
            @Override
            public Observable<List<OrdersSection>> call() {
                return Observable.just(dataExecute(list));
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<OrdersSection>>() {
            @Override
            public void call(List<OrdersSection> ordersSections) {
                mAdapter.setNewData(ordersSections);
            }
        });*/

    }


    private List<OrdersSection> dataExecute(List<ProductListEntity> list) {
        if (list == null) {
            return null;
        }
        List<OrdersSection> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ProductListEntity entity = list.get(i);
            list1.add(new OrdersSection(true, false, "header", entity));
            for (int j = 0; j < entity.getProduct().size(); j++) {
                ProductEntity product = entity.getProduct().get(j);
                product.setId(entity.getId());
                product.setTotalPrice(entity.getPrice());
                product.setStatus(entity.getStatus());
                list1.add(new OrdersSection(product));
            }
            list1.add(new OrdersSection(false, true, "foot", entity));
        }
        return list1;
    }

    @Override
    public void showLoading() {
        if (getUserVisibleHint()) {
            showProgressDialog();
        }
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        mIsLoadmore = false;
        mAdapter.notifyDataChangedAfterLoadMore(false);
        mIsRefresh = false;
        swipeLayoutMeReturnProduct.setRefreshing(false);
        loadDone();
        mList.clear();
        mAdapter.setNewData(mList);
        mAdapter.openLoadMore(false);
        if (getUserVisibleHint()) {
            T.showShort(App.getInstance(), msg);
        }
    }

    @Override
    public void onLoadMoreRequested() {
        recylerviewMeReturnProduct.post(new Runnable() {
            @Override
            public void run() {
                if (mIsLoadmore) {
                    return;
                }
                mIsLoadmore = true;
                mPage++;
                mPresenter.returnProduct(String.valueOf(mPage));
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {

    }

    private void loadDone() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_load_done, (ViewGroup) recylerviewMeReturnProduct.getParent(), false);
        mAdapter.addFooterView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ordersUpdate(OrdersEvent e) {
        initRequest();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
